package 力扣_排序算法.对Map中的value排序;

import java.util.*;

/**
 * @author zx
 * @create 2022-08-29 17:03
 */
public class 前K个高频单词 {
    public static List<String> topKFrequent(String[] words, int k) {
        List<String> res = new ArrayList<>();
        Map<String,Integer> map = new HashMap<>();
        for(int i = 0;i < words.length;i++){
            map.put(words[i],map.getOrDefault(words[i],0) + 1);
        }
        List<Map.Entry<String,Integer>> entries = new ArrayList<>(map.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if(o1.getValue() != o2.getValue()){
                    return o2.getValue() - o1.getValue();
                }else{
                    return o1.getKey().compareTo(o2.getKey());
                }
            }
        });
        for(int i = 0;i < k;i++){
            res.add(entries.get(i).getKey());
        }
        return res;
    }
}
